<template>
  <el-dialog v-model="visible" :title="!dataForm.categoryId ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="分类名称"></el-input>
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-popover :width="400" ref="categoriesListPopover" placement="bottom-start" trigger="click" popper-class="popover-pop">
          <template v-slot:reference>
            <el-input v-model="dataForm.parentName" :readonly="true" :placeholder="上级分类">
              <template v-slot:suffix>
                <el-icon @click.stop="deptListTreeSetDefaultHandle()" class="el-input__icon"><circle-close /></el-icon>
              </template> </el-input
          ></template>
          <div class="popover-pop-body"><el-tree :data="categoriesList" :props="{ label: 'name', children: 'children' }" node-key="categoryId" ref="categoriesTree" :highlight-current="true" :expand-on-click-node="false" accordion @current-change="deptListTreeCurrentChangeHandle"> </el-tree></div>
        </el-popover>
      </el-form-item>
      <el-form-item label="所属餐厅" prop="restaurantId">
        <el-select v-model="dataForm.restaurantId" value-key="restaurantId" :disabled="false" style="width: 100%" placeholder="选择所属餐厅">
          <el-option v-for="item in restaurantsList" :key="item.restaurantId" :label="item.name" :value="item.restaurantId"> </el-option>
        </el-select>
        <!-- <el-input v-model="dataForm.restaurantId" placeholder="所属餐厅"></el-input> -->
      </el-form-item>
      
      <el-form-item label="分类描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="分类描述"></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <el-radio-group v-model="dataForm.isActive" class="ml-4">
          <el-radio :label="1" size="large">启用</el-radio>
          <el-radio :label="0" size="large">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类图片URL" prop="imageUrl">
        <el-input v-model="dataForm.imageUrl" placeholder="分类图片URL"></el-input>
      </el-form-item>
      <el-form-item label="排序字段" prop="sortOrder">
        <el-input-number v-model="dataForm.sortOrder" controls-position="right" :min="0" :label="排序"></el-input-number>
        <!-- <el-input v-model="dataForm.sortOrder" placeholder="排序字段，默认值为0"></el-input> -->
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const categoriesList:any[] = ref();
const restaurantsList:any[] = ref();
const categoriesTree = ref();
const categoriesListPopover = ref();

const dataForm = reactive({
  categoryId: "",
  parentId: "",
  restaurantId: "",
  name: "",
  description: "",
  isActive: "",
  imageUrl: "",
  sortOrder: "",
  createdAt: "",
  updatedAt: "",
  creator: "",
  updater: "",
  parentName: ""
});

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  parentName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  categoryId: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  // restaurantId: [{ required: true, message: t("validate.required"), trigger: "blur" }],
});

const init = (categoryId?: number) => {
  visible.value = true;
  dataForm.categoryId = categoryId;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  // 获取分类列表,后获取详情信息
  getCategoriesList().then(() => {
    if (categoryId) {
      getInfo(categoryId);
      
    }
  });
  // 获取餐厅信息
  getRestaurantsList();
};

// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data: IObject) => {
  dataForm.parentId = data.categoryId;
  dataForm.parentName = data.name;
  categoriesListPopover.value.hide();
};

const deptListTreeSetDefaultHandle = () => {
  dataForm.parentId = null;
  dataForm.parentName = "一级分类";
};

// 获取分类列表
const getCategoriesList = () => {
  return baseService.get("/sys/categories/list").then((res) => {
    if (res.code !== 200) {
      return ElMessage.error(res.message);
    }
    categoriesList.value = res.data;
  });
};
// 获取餐厅信息
const getRestaurantsList = () => {
  return baseService.get("/sys/restaurants/page", {"order": null, "orderField": null,"page": 1, "limit": 10000}).then((res) => {
    if (res.code !== 200) {
      return ElMessage.error(res.message);
    }
    restaurantsList.value = res.data.list;
  });
};

// 获取信息
const getInfo = (categoryId: number) => {
  baseService.get("/sys/categories/" + categoryId).then((res) => {
    Object.assign(dataForm, res.data);

    categoriesTree.value.setCurrentKey(dataForm.parentId);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    
    (!dataForm.categoryId ? baseService.post : baseService.put)("/sys/categories", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>